'use strict';

const Service = require('egg').Service;
const { parseTime } = require('../utils/index');
const { v4: uuidv4 } = require('uuid');
const { getFileRedis, removeFileRedis } = require('../common/file');
const rabbitmq = require('../common/Queue');
const {publishMessage} = rabbitmq;

class HomeService extends Service {
  async login(openId, nickName, avatarUrl) {
    const { ctx, app } = this;
    //2022-2-2 功能变更
    // const Appid = 'wx5e0370a2c1a83969';
    // const SECRET = '917be58e779b9146185b43646a18294b';
    // const JSCODE = code;
    // const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${Appid}&secret=${SECRET}&js_code=${JSCODE}&grant_type=authorization_code`
    // const result = await ctx.curl(url, { dataType: 'json' });
    // //如果拿到授权则判断改用户是否注册
    // const { openId } = result.data;
    //查询数据库
    const user = await app.mysql.get('user', { openId });
    if (!user) {
      const save = await app.mysql.insert('user', {
        openId,
        avatarUrl,
        nickName,
        createDate: parseTime(new Date())
      });
    }
    //const result = await app.mysql.query('SELECT openId, nickName, avatarUrl, FROM user WHERE openId=?', [openId]);
    //进行签名
    //签名
    const token = await app.jwt.sign(
      {
        openId,
        time: Date.now(),
      },
      app.config.jwt.secret,
      {
        expiresIn: '1h',
      }
    );
    return { code: 200, msg: '', status: 'success', data: user, token };
  }

  async submitOrder(open_id, parameter) {
    const { app } = this;
    const order_id = uuidv4();
    const parameter_id = uuidv4();
    const { school_id,file_ids, shop_id, program, address_id, color, direction, paper, page, remark } = parameter;
    //存储打印参数
    const saveParameter = await app.mysql.insert('parameter', {
      parameter_id,
      shop_id,
      color,
      direction,
      paper,
      page,
      remark
    });
    //存储订单信息
    const saveOrder = await app.mysql.insert('orders', {
      order_id,
      shop_id,
      create_time: parseTime(new Date()),
      program,
      status: 0,
      address_id,
      price: 0,
      pay_money: 0,
      num: 10,
      parameterId: parameter_id,
      open_id,
    });
    //将已经上传的文件从redis中取出并且存入数据库中
    const ids = file_ids.split(',');
    await ids.forEach(async (item) => {
      const file = await getFileRedis(item, app);
      const saveResult = await app.mysql.insert('file', {
        ...file,
        order_id
      });
      if (saveResult.affectedRows === 1) {
        await removeFileRedis();
      }
    });
    //推送消息
    publishMessage(school_id,shop_id,shop_id,order_id);
    return { code: 200, msg: '', status: 'success', data: { order_id } };
  }

  async getSimpleOrders(open_id, page, limit) {
    const { ctx, app } = this;
    page = parseInt(page) || 1;
    limit = parseInt(limit) || 5;
    let offset = (page - 1) * limit
    //执行SQL语句
    const result = await app.mysql.query('SELECT order_id AS orderId,shop_name AS shopName,address,program,`status`,complete_time AS completeTime,price,orders.create_time AS createTime FROM `orders`,shop WHERE orders.shop_id = shop.shop_id AND orders.open_id = ? ORDER BY orders.create_time DESC LIMIT ?,?', [open_id, offset, limit]);
    //判断是否有下一页
    const hasNext = await app.mysql.query('SELECT COUNT(1) AS Count  FROM orders WHERE open_id = ?', [open_id]);
    const total = hasNext[0].Count;
    const totalPage = Math.ceil(total / limit);
    return ctx.body = { code: 200, msg: '', status: 'success', hasNextPage: page < totalPage, data: result };
  }

  async getDetailOrder(order_id) {
    const { ctx, app } = this;
    let detailAddress = '';
    const result = await app.mysql.query('SELECT order_id AS orderId,shop_name AS shopName,phone,complete_time AS completeTime,orders.create_time AS createTime,program,price,pay_money AS payMoney,address,`status`,num,color,direction,paper,page,remark    FROM orders,shop,parameter WHERE orders.shop_id = shop.shop_id AND  orders.parameterId = parameter.parameter_id AND order_id=?', [order_id]);
    const files = await app.mysql.query('SELECT file_id AS fileId,file_name AS fileName,school_id AS schoolId,shop_id AS shopId,open_id AS openId,view_path AS viewPath,upload_time AS uploadTime FROM file WHERE order_id=?', [order_id]);
    const address = await app.mysql.query('SELECT detail_address AS detailAddress FROM orders , address WHERE order_id=? AND  orders.address_id=address.address_id', [order_id]);
    if (address.length > 0) {
      detailAddress = address[0].detailAddress
    }
    if (result.length <= 0) {
      return { code: 200, msg: '获取详情失败!', status: 'failure' }
    } else {
      return {
        code: 200, msg: '', status: 'success', data: {
          ...result[0],
          files,
          detailAddress
        }
      }
    }

  }

  async getAddress(open_id, page, limit) {
    const { ctx, app } = this;
    page = parseInt(page) || 1;
    limit = parseInt(limit) || 5;
    const result = await app.mysql.query('SELECT address_id AS addressId,open_id AS openId,`name`,phone,area,detail_address AS detailAddress,create_time AS createTime,is_default AS isDefault FROM address WHERE open_id = ? ORDER BY create_time DESC LIMIT ?,?', [open_id, (page - 1) * limit, limit]);
    const hasNext = await app.mysql.query('SELECT COUNT(1) AS Count  FROM address WHERE open_id = ? ', [open_id]);
    const total = hasNext[0].Count;
    const totalPage = Math.ceil(total / limit);
    return { code: 200, msg: '', status: 'success', hasNextPage: page < totalPage, data: result };
  }

  async getAddressDetail(address_id) {
    const { ctx, app } = this;
    const result = await app.mysql.query('SELECT address_id AS addressId,open_id AS open_id,`name`,phone,area,detail_address AS detailAddress,create_time AS createTime,is_default AS isDefault FROM address WHERE address_id=?', [address_id]);
    if (result.length > 0) {
      return { code: 200, msg: '', status: 'success', data: result[0] };
    } else {
      return { code: 200, msg: '', status: 'failure', data: {} }
    }
  }

  async increaseAddress(open_id, data) {
    const { ctx, app } = this;
    const address_id = uuidv4();
    const result = await app.mysql.insert('address', {
      address_id,
      open_id,
      ...data,
      create_time: parseTime(new Date())
    });
    if (result.affectedRows === 1) {
      return { code: 200, msg: '', status: 'success', data: { addressId: address_id } }
    } else {
      return { code: 200, msg: '添加地址失败 请刷新页面重试!', status: 'failure' }
    }
  }

  async updateAddress(address_id, data) {
    const { ctx, app } = this;
    const options = {
      where: {
        address_id
      }
    };
    const result = await app.mysql.update('address', data, options);
    if (result.affectedRows === 1) {
      return { code: 200, msg: '', status: 'success', data: { addressId: address_id } }
    } else {
      return { code: 200, msg: '修改地址失败 请刷新页面重试!', status: 'failure' }
    }
  }

  async deleteAddress(address_id) {
    const { ctx, app } = this;
    const result = await app.mysql.delete('address', { address_id });
    if (result.affectedRows === 1) {
      return { code: 200, msg: '', status: 'success' }
    } else {
      return { code: 200, msg: '删除地址失败 请刷新页面重试!', status: 'failure' }
    }
  }

  async setDefaultAddress(address_id, open_id) {
    const { ctx, app } = this;
    //先全部设置为0
    const setZero = await app.mysql.update('address', { is_default: 0 }, { where: { open_id } });
    if (!setZero.affectedRows === 1) {
      return { code: 200, msg: '设置默认地址失败!', status: 'failure' }
    }
    const result = await app.mysql.update('address', { is_default: 1 }, { where: { address_id } });
    return result.affectedRows === 1 ? { code: 200, msg: '', status: 'success' } : { code: 200, msg: '设置默认地址失败!', status: 'failure' }
  }

  async getPickerDatas() {
    const { app } = this;
    const areas = await app.mysql.query('SELECT area_name AS areaName,area_id AS areaId FROM area;');
    const columnData = [];
    const schools = await app.mysql.query('SELECT school_id AS schoolId , school_name AS schoolName,area_code AS areaCode FROM school');
    areas.forEach((item) => {
      const items = [];
      schools.forEach((school) => {
        if (item.areaId == school.areaCode) {
          items.push(school)
        }
      });
      columnData.push(items);
    });
    const columns = [];
    columns.push(areas);
    if (columnData.length > 0) {
      columns.push(columnData[0]);
    }
    return { code: 200, msg: '', status: 'success', data: { columns, columnData } };
  }

  async updateSelectSchool(open_id, school_id) {
    const { app } = this;
    const result = await app.mysql.query('UPDATE user SET school_id=? WHERE openId=?', [school_id, open_id]);
    return result.affectedRows === 1 ? { code: 200, msg: '', status: 'success' } : { code: 200, msg: '修改所属学校失败!', status: 'failure' }

  }

  async getUserInfo(open_id) {
    const { app } = this;
    const result = await app.mysql.query('SELECT openId,avatarUrl,nickName,createDate,school_id AS schoolId FROM user WHERE openId=?', [open_id]);
    return result.length > 0 ? { code: 200, msg: '', status: 'success', data: { ...result[0] } } : { code: 200, msg: '', status: 'failure' }
  }

  async getShopBySchoolId(school_id) {
    const { app } = this;
    const result = await app.mysql.query('SELECT shop_id AS shopId,shop_name AS shopName FROM shop WHERE school_id=?', [school_id]);
    return { code: 200, msg: '', status: 'success', data: result };
  }

  async getSelectSchoolInfo(school_id) {
    const { app } = this;
    const result = await app.mysql.query('SELECT area_code AS areaCode,school_id AS schoolId,school_name AS schoolName,address FROM school WHERE school_id=?', [school_id]);
    if (result.length > 0) {
      return { code: 200, msg: '', status: 'success', data: result[0] }
    } else {
      return { code: 200, msg: '', status: 'failure', data: {} }
    }

  }
}
module.exports = HomeService;